<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="应用名" prop="name">
            <el-input
               v-model="queryParams.name"
               placeholder="请输入应用名"
               clearable
               style="width: 200px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="应用标识" prop="appKey">
            <el-input
               v-model="queryParams.appKey"
               placeholder="请输入应用标识"
               clearable
               style="width: 200px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="开启状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="开启状态" clearable style="width: 200px">
               <el-option
                  v-for="dict in dict.type.general_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['system:commonIssue:add']"
            >新增</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="list">
         <el-table-column label="序号" align="center" type="index" />
         <el-table-column label="应用名" align="center" prop="name" show-overflow-tooltip />
         <el-table-column label="应用标识" align="center" prop="appKey"  />
         <el-table-column label="开启状态" align="center" prop="status" >
            <template slot-scope="{row}">
               <dict-tag :options="dict.type.general_status" :value="row.status" />
            </template>
         </el-table-column>
         <el-table-column label="支付渠道" align="center">
           <el-table-column
             prop="appInfo"
             :label="item.label" align="center" show-overflow-tooltip
             v-for="(item,index) in qudaoList" :key="index"
             width="150">
             <template slot-scope="{row}">
               <div v-if="row.appInfo" @click="appConfg(row,item)" class="flex_zhcenter" style="width: 100%;">
                <div v-if="row.appInfo[item.value]">
                  <div class="dagou flex_zhcenter"
                  v-if="row.appInfo[item.value].status == 1"><i class="el-icon-check"></i></div>
                  <div class="chacha flex_zhcenter" v-else><i class="el-icon-close"></i></div>
                </div>
                <div class="chacha flex_zhcenter" v-else><i class="el-icon-close"></i></div>
               </div>
               <div @click="appConfg(row,item)" class="flex_zhcenter" style="width: 100%;" v-else>
                 <div class="chacha flex_zhcenter" ><i class="el-icon-close"></i></div>
               </div>
             </template>
           </el-table-column>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime"  />
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
               v-hasPermi="['system:commonIssue:edit']">修改</el-button>
               <el-button link type="primary" icon="Delete"
               @click="handleDelete(scope.row)" v-hasPermi="['system:commonIssue:remove']" >删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改公告对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
         <el-form ref="formRef" :model="form" :rules="rules"
         :label-width="title == '新增支付渠道信息' || title == '修改支付渠道信息' ? '120px' : '80px'">
            <el-row v-if="title == '新增支付渠道信息' || title == '修改支付渠道信息'">
               <el-col :span="24">
                <el-form-item label="appId" prop="config.appId">
                   <el-input v-model="form.config.appId" placeholder="请输入appId" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="商户号" prop="config.mchId">
                   <el-input v-model="form.config.mchId" placeholder="请输入商户号" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="服务商模式下的子商户公众账号ID" prop="config.subAppId">
                   <el-input v-model="form.config.subAppId" placeholder="请输入服务商模式下的子商户公众账号ID" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="服务商模式下的子商户号" prop="config.subMchId">
                   <el-input v-model="form.config.subMchId" placeholder="请输入服务商模式下的子商户号" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="证书路径" prop="config.privateKeyPath">
                   <el-input v-model="form.config.privateKeyPath" placeholder="请输入证书路径" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="apiV3 密钥值" prop="config.apiV3Key">
                   <el-input v-model="form.config.apiV3Key" placeholder="请输入apiV3 密钥值" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="证书序列号" prop="config.certSerialNo">
                   <el-input v-model="form.config.certSerialNo" placeholder="请输入证书序列号" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="开启状态" prop="status">
                   <el-radio-group v-model="form.status">
                      <el-radio
                         v-for="dict in dict.type.general_status"
                         :key="dict.value"
                         :label="Number(dict.value)"
                      >{{ dict.label }}</el-radio>
                   </el-radio-group>
                </el-form-item>
               </el-col>
            </el-row>
            <el-row v-else>
               <el-col :span="24">
                <el-form-item label="应用名" prop="name">
                   <el-input v-model="form.name" placeholder="请输入应用名" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="应用标识" prop="appKey">
                   <el-input v-model="form.appKey" placeholder="请输入应用标识" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="	备注" prop="remark">
                   <el-input v-model="form.remark" type="textarea" :rows="6" placeholder="请输入	备注" />
                </el-form-item>
               </el-col>
               <el-col :span="24">
                <el-form-item label="开启状态" prop="status">
                   <el-radio-group v-model="form.status">
                      <el-radio
                         v-for="dict in dict.type.general_status"
                         :key="dict.value"
                         :label="Number(dict.value)"
                      >{{ dict.label }}</el-radio>
                   </el-radio-group>
                </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script>
import { listPayApp, getPayApp, addPayApp,
updatePayApp,delPayApp } from "@/api/paymentManage/payApplicatInfor";
import { getPayChannel, addPayChannel, updatePayChannel,
delPayChannel,getChannelByAppId } from "@/api/paymentManage/payChannels";
export default {
  name: 'PayApplicatInfor',
  dicts: ['general_status'],
  components: {  },
  data() {
    return {
      qudaoList:[
        {label:'微信 JSAPI 支付',value:'wx_pub',},
        {label:'微信 App 支付',value:'wx_app',},
      ],
      form: {},// 表单参数
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      queryParams: {// 查询参数
        pageNum: 1,
        pageSize: 10,
        status:null,
        appKey:null,
        name:null,
      },
      // 总条数
      total: 0,
      rules: {
        name: [{ required: true, message: "应用名不能为空", trigger: "blur" }],
        appKey: [{ required: true, message: "应用标识不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "change" }],

        config: [{ required: true, message: "appId不能为空", trigger: "blur" }],
      },
      list:[],//页面数据
    };
  },
  mounted(){
    this.getList()
  },
  methods: {
    appConfg(row,item){//配置app
      this.reset();
      this.form = {
        appId:row.id,
        channelCode:item.value,
        config:{},
        status:1,
      }
      if(row.appInfo[item.value]) {
        let id = row.appInfo[item.value].id
        if(id){
          this.title = "修改支付渠道信息";
          getPayChannel(id).then(response => {
            let data = response.data || {}
            this.form = {
              ...data,
            };
          });
        }else{
          this.title = "新增支付渠道信息";
        }
      }else{
        this.title = "新增支付渠道信息";
      }
      this.open = true;
    },
    async getChannelByAppId(appId,index,rows){
      let res = await getChannelByAppId({appId})
      let data = res.data || []
      let arr = []
      this.qudaoList.map(item=>{
        let obj = data.find(item1=>item1.channelCode == item.value)
        arr[item.value] = obj ? {...obj} : {}

      })
      rows[index].appInfo = arr
      if(rows.length - 1 === index) {
        this.list = [...rows]
        this.loading = false;
      }
      if(rows.length - 1 >= index + 1) {
        this.getChannelByAppId(rows[index + 1].id,index + 1,rows)
      }
      return data
    },
    getList() {
      this.loading = true;
      this.list = []
      listPayApp(this.queryParams).then(async response => {
        let rows = response.rows || [];
        if(rows.length) {
          this.getChannelByAppId(rows[0].id,0,rows)
        }else{
          this.list = []
          this.loading = false;
        }
        this.total = response.total || 0;
      });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.open = true;
      this.reset();
      this.title = "添加支付应用信息";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.open = true;
      this.title = "修改支付应用信息";
      getPayApp(id).then(response => {
        let data = response.data || {}
        this.form = {...data,};
      });
    },
    // 表单重置
    reset() {
      this.form = {status:1};
      this.resetForm("formRef");
    },
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if(this.title == '新增支付渠道信息' || this.title == '修改支付渠道信息') {
            let api = this.form.id ? updatePayChannel : addPayChannel
            api(form).then(response => {
              this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
              this.open = false;
              this.getList();
            });
          }else{
            if (this.form.id != undefined) {
              updatePayApp(form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false;
                this.getList();
              });
            } else {
              addPayApp(form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false;
                this.getList();
              });
            }
          }

        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleDelete(row) {//删除
      const del_ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + del_ids + '"的数据项？').then(function() {
        return delPayApp(del_ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },
  }
}
</script>
<style scoped>
  .dagou,.chacha{
    width: 30px;height: 30px;border-radius: 50%;
    color: #fff;cursor: pointer;
  }
  .dagou{background-color: #67C23A;}
  .chacha{background-color: #F46B6C;}
</style>
